var canvas;
var canvasContext;
var loggedInImage;

var loadingAnimation = new LoadingAnimation();



//Animation code very slightly modified from the Google Chrome Google Mail Checker Extension
//http://code.google.com/chrome/extensions/samples.html
function LoadingAnimation() {
	this.timerId_ = 0;
	this.maxCount_ = 8;  // Total number of states in animation
	this.current_ = 0;  // Current state
	this.maxDot_ = 4;  // Max number of dots in animation
}

LoadingAnimation.prototype.paintFrame = function(tabId) {
	var text = "";
	for (var i = 0; i < this.maxDot_; i++) {
 		text += (i == this.current_) ? "." : " ";
	}
	if (this.current_ >= this.maxDot_)
 		text += "";

	chrome.browserAction.setBadgeText({text:text, tabId: tabId});
	this.current_++;
	if (this.current_ == this.maxCount_)
		this.current_ = 0;
}

LoadingAnimation.prototype.start = function(tabId) {
	if (this.timerId_)
		return;

	var self = this;
	this.timerId_ = window.setInterval(function() {
 		self.paintFrame(tabId);
	}, 100);
}

LoadingAnimation.prototype.stop = function() {
	if (!this.timerId_)
		return;

	window.clearInterval(this.timerId_);
	this.timerId_ = 0;
}

$(document).ready(function() {
	//Show options on first load (to initialize parameters)
	if(!localStorage.pdfCrowdOptions) {
		chrome.tabs.create( {url:"options.html"} );
	}
	//Don't show updated for version 1.4.6 - leave at 1.4.2
	var version = "1.7.0";
	//Show updated page first load
	if(!localStorage.updatedToVersion || localStorage.updatedToVersion != version) {
			chrome.tabs.create( {url:"updated.html"} );
			localStorage.updatedToVersion = version;
	}

	canvas = document.getElementById('canvas');
	loggedInImage = document.getElementById('loaded_icon');
	canvasContext = canvas.getContext('2d');

	chrome.browserAction.onClicked.addListener(clickHandler);
	//Create one test item for each context type.
	//chrome.contextMenus.create({"title": "Send page to Google Docs", "contexts":["page"], "onclick": contextPageUrlHandler});
	//chrome.contextMenus.create({"title": "Send frame to Google Docs", "contexts":["frame"], "onclick": contextFrameUrlHandler});
	//chrome.contextMenus.create({"title": "Send link to Google Docs", "contexts":["link"], "onclick": contextLinkUrlHandler});
	//chrome.contextMenus.create({"title": "Send image to Google Docs", "contexts":["image"], "onclick": contextMediaHandler});
	//chrome.contextMenus.create({"title": "Send video to Google Docs", "contexts":["video"], "onclick": contextMediaHandler});
	//chrome.contextMenus.create({"title": "Send audio to Google Docs", "contexts":["audio"], "onclick": contextMediaHandler});
	//chrome.contextMenus.create({"title": "Send other to Google Docs", "contexts":["all"], "onclick": contextPageUrlHandler});
});

function contextPageUrlHandler( info, tab ) {
	chrome.browserAction.setBadgeBackgroundColor({color:[108, 186, 217, 255], tabId: tab.id});
	loadingAnimation.start(tab.id);
	var url = info.pageUrl;
	checkContentAndSaveToDocs( tab.id, url, tab.title, tab.index );
}
function contextFrameUrlHandler( info, tab ) {
	chrome.browserAction.setBadgeBackgroundColor({color:[108, 186, 217, 255], tabId: tab.id});
	loadingAnimation.start(tab.id);
	var url = info.frameUrl;
	checkContentAndSaveToDocs( tab.id, url, tab.title, tab.index );
}
function contextLinkUrlHandler( info, tab ) {
	chrome.browserAction.setBadgeBackgroundColor({color:[108, 186, 217, 255], tabId: tab.id});
	loadingAnimation.start(tab.id);
	var url = info.linkUrl;
	checkContentAndSaveToDocs( tab.id, url, tab.title, tab.index );
}
function contextMediaHandler( info, tab ) {
	chrome.browserAction.setBadgeBackgroundColor({color:[108, 186, 217, 255], tabId: tab.id});
	loadingAnimation.start(tab.id);
	var url = info.srcUrl;
	sendUrlToDocs( tab.id, url, tab.title, tab.index, false);
}

function clickHandler(tab) {
	chrome.browserAction.setBadgeBackgroundColor({color:[108, 186, 217, 255], tabId: tab.id});
	loadingAnimation.start(tab.id);
	checkContentAndSaveToDocs(tab.id, tab.url, tab.title, tab.index);
}

function checkContentAndSaveToDocs(tabId, url, title, tabIndex) {
	var d = new Date();
	console.log("Before request:" + d.toLocaleTimeString());
	$.ajax({
		type: "GET",
		url: url,
		success: function(responseData, status, request){
			var d = new Date();
			var contentType = request.getResponseHeader("Content-Type");
			request.abort();
			
			var isHtml = false;
			if(contentType != null && contentType.indexOf("html") >= 0) {
				isHtml = true;
			}
			if(isHtml) {
				sendUrlToDocs(tabId, url, title, tabIndex, true);
			}
			else {
				sendUrlToDocs(tabId, url, title, tabIndex, false);
			}
			
		},
		error: function(request, textStatus, errorThrown) {
			console.log("Error:" + d.toLocaleTimeString());
			var error = "Error processing pdf conversion from pdfcrowd.com";
			var errorMessage = textStatus;
			if(errorMessage == null) {
				if(request.responseText != null) {
					var message = request.responseText;
					if(message.length > 50) {
						message = message.substring(0,50) + "...";
					}
					 error += " - " + message;
				}
			}
			else {
				 error += " - " + errorMessage;
			}
				
			setError(tabId, error);
		}
	});
}

function sendUrlToDocs(tabId, url, title, tabIndex, convertToPdf) {
	var rex = /^((?:chrome|file|chrome-extension|about):.*$)/i;
	var result = rex.exec(url);
	if (result) {
		setError(tabId, "Conversion of local URLs is not supported (" + result[1] + ").");
		return;
	}
	title = title.replace("?", "");

	if(!convertToPdf) {
		var googleViewerUrl = "https://drive.google.com/viewer?&url=" + url;
		chrome.tabs.create({url:googleViewerUrl, index:tabIndex}, function(tab) {
			chrome.browserAction.setBadgeText({text: ":)", tabId: tabId});
			chrome.browserAction.setTitle({title: "Upload Successful", tabId: tabId});
			loadingAnimation.stop();
		});
	}
	else if(localStorage['pdfCrowdOptions'] == "usePdfCrowdAccount") {
		_gaq.push(['_trackEvent', 'PDF Request', 'Extension Defaults Request']);
		var username = localStorage['username'];
		var key = localStorage['token'];
		$.ajax({
			type: "POST",
			url: "http://pdfcrowd.com/api/json/convert/uri/",
			data: "username=" + username + "&key=" + key + "&src=" + escape(url) + "&height=-1&width=508 mm&initial_pdf_zoom_type=1&page_orientation=landscape&page_format=letter",
			dataType: "json",
			success: function(responseData, status, request){
				var downloadUrl = "https://pdfcrowd.com" + responseData.path + "/" + escape(title) + ".pdf";
				var googleViewerUrl = "https://drive.google.com/viewer?url=" + downloadUrl;
				chrome.tabs.create({url:googleViewerUrl, index:tabIndex}, function(tab) {
					chrome.browserAction.setBadgeText({text: ":)", tabId: tabId});
					chrome.browserAction.setTitle({title: "Upload Successful", tabId: tabId});
					loadingAnimation.stop();
				});
			},
			error: function(request, textStatus, errorThrown) {
				var error = "Error processing pdf conversion from pdfcrowd.com";
				var errorMessage = textStatus;
				if(errorMessage == null) {
					if(request.responseText != null) {
						var message = request.responseText;
						if(message.length > 50) {
							message = message.substring(0,50) + "...";
						}
						 error += " - " + message;
					}
				}
				else {
					 error += " - " + errorMessage;
				}
					
				setError(tabId, error);
			}
		});
	}
	else if(localStorage['pdfCrowdOptions'] == "usePdfCrowdNoAccount"){
		_gaq.push(['_trackEvent', 'PDF Request', 'pdfcrowd Defaults Request']);
		var authenticated = isPdfCrowdAuthenticated();
		if(authenticated) {
			setError(tabId, "Please sign out of PdfCrowd or change the extension options.");
		} else {
			pdfCrowdSessionRequest(tabId, url, title, tabIndex);
		}
	}
	else if(localStorage['pdfCrowdOptions'] == "usePdfCrowdSession"){
		_gaq.push(['_trackEvent', 'PDF Request', 'User Account Defaults Request']);
		var authenticated = isPdfCrowdAuthenticated();
		if(!authenticated) {
			setError(tabId, "Please sign in to PdfCrowd or change the extension options.");
		} else {
			pdfCrowdSessionRequest(tabId, url, title, tabIndex);
		}
	}
	else {
		setError(tabId, "Error processing PdfCrowd Options");
	}
}

function pdfCrowdSessionRequest(tabId, url, title, tabIndex) {
	$.ajax({
		type: "POST",
		url: "http://pdfcrowd.com/session/json/convert/uri/",
		data: "src=" + escape(url),
		dataType: "json",
		success: function(responseData, status, request){
			if(responseData.status == "ok") {
				//pdfcrowd added a feature that allows an arbitrary /something.pdf to
				//trick the google drive viewer to saving it with the right name.
				var pathEnd = responseData.url.indexOf("?name=");
				if(pathEnd == -1) {
					setError(tabId, "Couldn't parse pdfcrowd response url.");
					return;
				}
				var downloadUrl = responseData.url.substring(0, pathEnd);
				downloadUrl += "/" + escape(title) + ".pdf";
				var googleViewerUrl = "https://drive.google.com/viewer?url=" + downloadUrl;
				chrome.tabs.create({url:googleViewerUrl, index:tabIndex}, function(tab) {
					chrome.browserAction.setBadgeText({text: ":)", tabId: tabId});
					chrome.browserAction.setTitle({title: "Upload Successful", tabId: tabId});
					loadingAnimation.stop();
					_gaq.push(['_trackEvent', 'PDF Request', 'Successful Upload']);
				});
			}
			else if(responseData.status == "redirect"){
				var error = "Error processing pdf conversion from pdfcrowd.com - See the newly opened pdfcrowd tab for more information.";
				chrome.tabs.create({url:responseData.url, index:tabIndex}, function(tab) {
					setError(tabId, error);
				});
			}
			else {
				var error = "Error processing pdf conversion from pdfcrowd.com";
				if(responseData.message != null) {
					var message = responseData.message;
					if(message.length > 50) {
						message = message.substring(0,50) + "...";
					}
					 error += " - " + message;
				}
				setError(tabId, error);
			}
		},
		error: function(request, textStatus, errorThrown) {
			var error = "Error processing pdf conversion from pdfcrowd.com";
			var errorMessage = textStatus;
			if(errorMessage == null) {
				if(request.responseText != null) {
					var message = request.responseText;
					if(message.length > 50) {
						message = message.substring(0,50) + "...";
					}
					 error += " - " + message;
				}
			}
			else {
				 error += " - " + errorMessage;
			}
				
			setError(tabId, error);
		}
	});
}

function isPdfCrowdAuthenticated() {
	var authenticated = null;
	$.ajax({
		type: "GET",
		async: false,
		url: "http://pdfcrowd.com/session/json/user/",
		dataType: "json",
		success: function(responseData, status, request){
			authenticated = responseData.authenticated;
		},
	});
	return authenticated;
}

function setError(tabId, errorMessage) {
	chrome.browserAction.setBadgeBackgroundColor({color:[208, 0, 24, 255], tabId: tabId});
	chrome.browserAction.setBadgeText({text: "!", tabId: tabId});
	if(errorMessage != null && errorMessage != "") {
		chrome.browserAction.setTitle({title: errorMessage, tabId: tabId});
	}
	_gaq.push(['_trackEvent', 'PDF Request', 'Error', errorMessage]);
	loadingAnimation.stop();
}